import ulogger
import gc
from micropython import alloc_emergency_exception_buf
alloc_emergency_exception_buf(128)

class WebFileManager:
    def __init__(self, logger: ulogger.Logger=None):
        if logger is not None:
            self.logger = logger
        else:
            self.logger = ulogger.Logger('webfile')
            
        self.webserver = None

    def start_file_server(self):
        gc.collect()

        # Start WWW serveru
        from .web_server import WebServer

        self.webserver = WebServer(web_folder='/web_file_manager_www', port=80, logger=self.logger)

        # handlers for filemanager
        from . import file_manager

        @self.webserver.handle('/contents')
        def _handle_contents(client, path, request):
            file_manager.handle_contents(client, path, request)

        @self.webserver.handle('/upload')
        def _handle_upload(client, path, request):
            file_manager.handle_upload(client, path, request)

        @self.webserver.handle('/download')
        def _handle_download(client, path, request):
            file_manager.handle_download(client, path, request)

        @self.webserver.handle('/delete')
        def _handle_delete(client, path, request):
            file_manager.handle_delete(client, path, request)

        @self.webserver.handle('/rename')
        def _handle_rename(client, path, request):
            file_manager.handle_rename(client, path, request)

        @self.webserver.handle('/newfolder')
        def _handle_newfolder(client, path, request):
            file_manager.handle_newfolder(client, path, request)

        @self.webserver.handle('/move')
        def _handle_move(client, path, request):
            file_manager.handle_move(client, path, request)

        @self.webserver.handle('/copy')
        def _handle_copy(client, path, request):
            file_manager.handle_copy(client, path, request)

        @self.webserver.handle('/status')
        def _handle_status(client, path, request):
            file_manager.handle_status(client, path, request)


        @self.webserver.handle('/writefile')
        def _handle_writefile(client, path, request):
            file_manager.handle_writefile(client, path, request)
            
        @self.webserver.handle('/restart')
        def _handle_restart(client, path, request):
            file_manager.handle_restart(client, path, request)


        self.webserver.start()

        gc.collect()

    def stop_file_server(self):
        self.webserver.stop()
        gc.collect()